import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { LoveRecycManageService } from '../love-recyc-manage.service';

@Component({
  selector: 'app-love-class-select',
  templateUrl: './love-class-select.component.html',
  styleUrls: ['./love-class-select.component.scss']
})
export class LoveClassSelectComponent implements OnInit {

  // seach form
  seachParams: any = {
    category: '', // 所属品类 1：手机 2：平板
    name: '',
    status: '' // 0：禁用，1：启用
  };

  tableData: any = [];
  tableParams: any = {
    tableLoading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };

  // Modal
  validateForm!: FormGroup;
  isVisible: boolean = false;
  modalType: number = 0; // 0：新增，1：编辑
  modalItem: any = {};
  subModalLoding: boolean = false;
  uploadLoading: boolean = false;

  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private services: LoveRecycManageService
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      category: ['', [Validators.required]],
      name: ['', [Validators.required]],
      sort: ['', [Validators.required]],
      status: ['', [Validators.required]]
    });

    this.loadTable();
  }

  // Table Data
  async loadTable() {
    try {
      let params: any = {
        ...this.seachParams,
        // page: this.tableParams.page,
        // pageSize: this.tableParams.pageSize
      }
      this.tableParams.tableLoading = true;
      const res: any = await this.services.getClassSelectList(params);
      this.tableParams.tableLoading = false;

      if (res.code == 0) {
        this.tableData = res.data || [];
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  seachData() {
    // this.tableParams.page = 1;
    this.loadTable();
  }
  resetData() {
    Object.keys(this.seachParams).forEach(key => {
      this.seachParams[key] = '';
    })
    this.loadTable();
  }

  // 删除
  async deleteItem(item: any) {
    try {
      let params = {
        id: item.id
      }
      const res: any = await this.services.deleteClassSelectItem(params);
      if (res.code == 0) {
        this.message.success('删除成功');
        this.loadTable();
      } else {
        this.message.error(res.message || '删除失败');
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  /**
   * 新增、编辑
   * @param num 0：新增，1：编辑
   * @param item 
   */
  showModal(num: number, item?: any) {
    if (num == 1) {
      this.modalItem = item;
      this.validateForm.patchValue({
        category: item.category,
        name: item.name,
        sort: item.sort,
        status: item.status
      });
    }
    this.modalType = num;
    this.isVisible = true;
  }

  handleCancel(): void {
    this.isVisible = false;
    this.validateForm.reset();
  }

  // modal submit
  submitForm(): void {
    if (this.validateForm.valid) {
      this.subFormInterface();
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }
  async subFormInterface() {
    try {
      let params: any = {
        ...this.validateForm.value
      }

      // 编辑
      if (this.modalType == 1) {
        params.id = this.modalItem.id;
      }
      this.subModalLoding = true;
      const res: any = await this.services.updateClassSelectItem(params);
      this.subModalLoding = false;

      if (res.code == 0) {
        this.message.success('操作成功');
        this.validateForm.reset();
        this.isVisible = false;
        this.loadTable();
      } else {
        this.message.error(res.message);
      }
    } catch (error: any) {
      this.message.error(error);
    }
  }

  // 当前页码改变时的回调函数
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  // 页数改变时的回调函数
  onPageSizeChange(sizeNum: number) {
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }
}
